<template>
    <!-- 个人资料对话框 -->
    <el-dialog
      v-model="componentVisible"
      :title="title"
      width="300"
      :draggable="true"
      :modal="false"
      @close="editMode = 0"
    >
      <div class="personal-data-container" v-if="editMode === 2">
        <div class="item">
          <div class="label">头像：</div>
          <div class="content">
            <el-upload
                  class="avatar-uploader"
                  :action="AttachmentApi.upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  name="file"
                  :headers="headers"
                  :data="data"
              >
                  <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
          </div>
        </div>
        <div class="item">
          <div class="label">姓名：</div>
          <div class="content"><el-input size="small" v-model="userForm.username" disabled/></div>
        </div>
        <div class="item">
          <div class="label">部门：</div>
          <div class="content"><el-input size="small" v-model="userForm.deptName" disabled/></div>
        </div>
        <div class="item">
          <div class="label">职位：</div>
          <div class="content"><el-input size="small" v-model="userForm.job" clearable/></div>
        </div>
      </div>
      <div class="personal-data-container" v-else>
        <div class="item">
          <div class="label">头像：</div>
          <div class="content">
            <el-avatar shape="square" :size="140" :src="user.avatar">{{ user.username }}</el-avatar>
          </div>
        </div>
        <div class="item">
          <div class="label">姓名：</div>
          <div class="content"><span>{{ user.username }}</span></div>
        </div>
        <div class="item">
          <div class="label">部门：</div>
          <div class="content"><span>{{ user.deptName }}</span></div>
        </div>
        <div class="item">
          <div class="label">职位：</div>
          <div class="content"><span>{{ user.job }}</span></div>
        </div>
      </div>
      <template #footer v-if="editMode != 0">
        <div class="dialog-footer">
          <el-button size="small" v-if="editMode === 1" type="success" @click="toEditMode">编辑</el-button>
          <el-button size="small" v-if="editMode === 2" type="info" @click="editMode = 1">取消</el-button>
          <el-button size="small" v-if="editMode === 2" type="primary" @click="doEditPersonalData">确认</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref,computed,defineProps,defineEmits } from 'vue';
import { AttachmentApi,UserApi } from '@/api/path';
import { $get,$post } from '@/utils/request';
import { $msg_e,$msg_s } from '@/utils/msg';
import { Plus } from '@element-plus/icons-vue';
import { UserState } from '@/store/loginUser';


const props = defineProps({
    // 标题
    title:String,
    // 是否可见
    visible:{
        type:Boolean,
        default:false
    },
    // 模式，0-默认，1-查看，2-编辑
    mode:{
        type:Number,
        default:0
    },
    // 用户信息（这个是只读属性）
    user:{
        type:Object,
        default:{}
    }
})
const emits = defineEmits({
    'update:visible':null,
    'update:mode':null
})

const componentVisible = computed({
    get: () => props.visible,
    set: (val) => {
        emits('update:visible', val);
    }
});

const editMode = computed({
    get: () => props.mode,
    set: (val) => {
        emits('update:mode', val);
    }
});

const userForm = ref({
    id:'',
    avatar:'',
    job:'',
    username:'',
    deptName:''
})

const headers = ref()
const data = ref()


const toEditMode = () => {
    userForm.value = {
        id: props.user.id,
        avatar: props.user.avatar,
        job: props.user.job,
        username: props.user.username,
        deptName: props.user.deptName
    }
    editMode.value = 2
}


const beforeAvatarUpload = file => {
    // console.log('beforeAvatarUpload-file: ', file);
    // 定义图片格式
    const imgTypes = ['image/jpeg','image/png','image/gif']
    // 是否图片
    const isImg = imgTypes.includes(file.type)
    // 大小是否小于2M
    const isLt2M = file.size / 1024 / 1024 < 2
    if(!isImg){
        $msg_e('请选择正确的图片格式')
    }
    if(!isLt2M){
        $msg_e('图片大小不能超过2MB')
    }
    if(isImg && isLt2M){
        headers.value = {'x-auth-token':window.localStorage.getItem('token')}
        data.value = {bizType: 'avatar', bizId: props.user.id}
        return true
    }else{
        return false
    }
}
const handleAvatarSuccess = res => {
    // console.log('handleAvatarSuccess-res: ', res);
    if(!res.success){
        return $msg_e(res.message)
    }
    userForm.value.avatar = res.data.previewUrl
    // console.log('avatarUploadSuccess: ', personalData.value);
    
}
const doEditPersonalData = async () => {
  const res = await $post(UserApi.updById, userForm.value);
  if(!res.success){
    return $msg_e(res.message)
  }
  $msg_s('修改成功')
  const _res = await $get(UserApi.getLoginUserInfo)
  if(!_res.success){
    return $msg_e(_res.message)
  }
  const userInfo = _res.data;
  UserState.setUserInfo(userInfo)
  componentVisible.value = false
}

</script>

<style scoped lang="scss">
/**个人资料对话框样式 */
.personal-data-container{
  --el-text-color-disabled: #CDC9C9;
  display: flex;
  flex-direction: column;
  justify-content: start;
  & > .item{
    display: flex;
    flex-direction: row;
    & > .label{
      width: 60px;
      display: flex;
      flex-direction: row;
      justify-content: end;
      align-items: center;
      font-size: 14px;
    }
    & > .content{
      flex: 1;
    }
  }
  & > .item:nth-child(-n+3){ 
    margin-bottom: 10px;
  }
}


/**头像上传控件样式（注意照搬官网的会有坑） */
.avatar-uploader { /**<el-upload>上传组件样式 */
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 140px;
  height: 140px;
}

.avatar-uploader:hover { /**<el-upload>上传组件鼠标移动上去时的样式 */
  border-color: #409eff;
}

.avatar-uploader .avatar { /**<img>图片样式 */
  width: 140px;
  height: 140px;
  display: block;
}

.el-icon.avatar-uploader-icon { /** + 加号样式 */
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 140px;
  text-align: center;
}
</style>